package com.topvision.common.security;

import com.topvision.common.token.RawAccessToken;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;

import java.util.Collection;

/**
 * @author shengwm
 * @version V0.0.1
 * @Title: CustomAuthenticationToken
 * @Package com.seed.common.security
 * @Description: 自定义授权Token
 * @date 2017/6/17
 */
public class CustomAuthenticationToken extends AbstractAuthenticationToken {
    private static final long serialVersionUID = 421112487331882681L;

    private RawAccessToken rawAccessToken;
    private UserInfo userInfo;

    public CustomAuthenticationToken(RawAccessToken rawAccessToken) {
        super(null);
        this.rawAccessToken = rawAccessToken;
        this.setAuthenticated(false);
    }

    public CustomAuthenticationToken(UserInfo userInfo, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.eraseCredentials();
        this.userInfo = userInfo;
        super.setAuthenticated(true);
    }

    @Override
    public void setAuthenticated(boolean authenticated) {
        if (authenticated) {
            throw new IllegalArgumentException(
                    "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        }
        super.setAuthenticated(false);
    }

    @Override
    public Object getCredentials() {
        return rawAccessToken;
    }

    @Override
    public Object getPrincipal() {
        return this.userInfo;
    }

    @Override
    public void eraseCredentials() {
        super.eraseCredentials();
        this.rawAccessToken = null;
    }
}
